﻿package com.valeosys {
	import flash.events.Event; 
	import flash.events.ErrorEvent; 
	import flash.events.IOErrorEvent; 
	import flash.events.SecurityErrorEvent; 
	import flash.events.SampleDataEvent;
	import flash.net.URLLoader; 
	import flash.net.URLRequest; 
	import flash.net.URLRequestMethod;
	import flash.net.URLLoaderDataFormat; 
	import flash.net.URLVariables; 

	public class RestServiceCall {
		public var requestor:URLLoader = new URLLoader(); 
		/*public function RestServiceCall() {
			//Create the HTTP request object 
			var request:URLRequest = new URLRequest( "http://service.example.com/" ); 
			request.method = URLRequestMethod.GET; 
			 
			//Add the URL variables 
			var variables:URLVariables = new URLVariables(); 
			variables.method = "test.echo"; 
			variables.api_key = "123456ABC"; 
			variables.message = "Able was I, ere I saw Elba.";             
			request.data = variables; 
			initiateTransaction(request);
			
		}
		public function RestServiceCall(url:String) {
			//Create the HTTP request object 
			var request:URLRequest = new URLRequest(url); 
			request.method = URLRequestMethod.GET; 
			 
			//Add the URL variables 
			var variables:URLVariables = new URLVariables(); 
			variables.method = "test.echo"; 
			variables.api_key = "123456ABC"; 
			variables.message = "Able was I, ere I saw Elba.";             
			request.data = variables; 
			initiateTransaction(request);
			
		}*/
		public function RestServiceCall(url:String, variables:URLVariables) {
			trace("Create the HTTP request object"); 
			var request:URLRequest = new URLRequest(url); 
			//request.method = URLRequestMethod.GET; 
			request.method = URLRequestMethod.POST; 
			request.data = variables; 
			initiateTransaction(request);
			
		}
		public function initiateTransaction(request:URLRequest):void {
			trace("Initiate the transaction");
			
			requestor = new URLLoader(); 
			//requestor.dataFormat = URLLoaderDataFormat.VARIABLES;
			requestor.addEventListener( Event.COMPLETE, httpRequestComplete ); 
			requestor.addEventListener( IOErrorEvent.IO_ERROR, httpRequestError ); 
			requestor.addEventListener( SecurityErrorEvent.SECURITY_ERROR, httpRequestError ); 
			requestor.load( request );
		}
		private function httpRequestComplete( event:Event ):void { 
			trace("httpRequestComplete");
			trace( event.target.data ); 
		} 
		private function httpRequestError( error:IOErrorEvent ):void { 
			trace( "An error occured: " + error.text );     
		}
		public function callRequest(url:String, variables:URLVariables):void {
			trace("callRequest"); 
			var request:URLRequest = new URLRequest(url); 
			//request.method = URLRequestMethod.GET; 
			request.method = URLRequestMethod.POST; 
			request.data = variables; 
			initiateTransaction(request);
		}
	}
}
